const Router = require('koa-router');
const fs = require('fs');
const mongoose = require('mongoose');
const router = new Router();

// 插入所有商品
router.get('/insertAllGoodsInfo', async(ctx) => {
  try {
    let data = fs.readFileSync('./data_json/newGoods.json', 'utf8');
    data=JSON.parse(data);
    let saveCount=0;    // 用于记录插入多少条数据
    const goods = mongoose.model('goods');
    await Promise.all(data.map(async (item) => {
      let newGoods = new goods(item);
      return await newGoods.save().then(() => {// 等待异步操作完成，返回执行结果
        saveCount++;
      }).catch(err => {
        console.log('失败'+err);
      })
    }))
    ctx.response.body = {code:0, msg:saveCount+'条商品详情已经全部插入到数据库之中了'}
  } catch (error) {
    console.log('商品详情写入数据库错误', error);
    ctx.response.body = {code:500, msg:'商品详情写入数据库错误'}
  }
})


// 插入所有分类
router.get('/insertAllCategory', async(ctx)=> {
  try {
    let data = fs.readFileSync('./data_json/category.json', 'utf8');
    data = JSON.parse(data);
    const category = mongoose.model('category');
    let saveCount = 0;
    await Promise.all(data.RECORDS.map(async(item, index) => {
      let newCategory = new category(item);
      await newCategory.save().then(() => {
        saveCount++;
      }).catch(err => {
        console.log('失败'+err);
      })
    }))
    ctx.response.body = {code:0, msg:saveCount+'条商品分类已经全部插入到数据库之中了'}
  } catch (error) {
    console.log('商品分类写入数据库错误', error);
    ctx.response.body = {code:500, msg:'商品分类写入数据库错误'}
  }
})

// 插入所有2级分类
router.get('/insertAllCategorySub', async(ctx)=> {
  try {
    let data = fs.readFileSync('./data_json/category_sub.json', 'utf8');
    data = JSON.parse(data);
    const categorySub = mongoose.model('categorySub');
    let saveCount = 0;
    await Promise.all(data.RECORDS.map(async(item, index) => {
      let newCategorySub = new categorySub(item);
      await newCategorySub.save().then(() => {
        saveCount++;
      }).catch(err => {
        console.log('失败'+err);
      })
    }))
    ctx.response.body = {code:0, msg:saveCount+'条商品2级分类已经全部插入到数据库之中了'}
  } catch (error) {
    console.log('商品2级分类写入数据库错误', error);
    ctx.response.body = {code:500, msg:'商品2级分类写入数据库错误'}
  }
})

// 根据商品ID获取商品详情
router.post('/getDetailGoodsInfo', async(ctx)=>{
  try {
    let goodsId = ctx.request.body.goodsId;
    const goods = mongoose.model('goods');
    let data = await goods.findOne({ID:goodsId}).exec();
    ctx.response.body = {code:0, data};
  } catch (error) {
    console.log('error', error);
    ctx.response.body = {code:500, data:error}
  }
})

// 获取商品分类列表
router.get('/getCategoryList', async(ctx) => {
  try {
    const Category = mongoose.model('category')
    let result = await Category.find().exec()
    ctx.body={code:0,message:result}
  } catch (error) {
    ctx.body={code:500,message:error}
  }
})

// 根据1级分类ID，获取商品2级分类列表
router.post('/getCategorySubList', async(ctx) => {
  try{
    let categoryId = ctx.request.body.categoryId
    const CategorySub = mongoose.model('categorySub')
    let result = await CategorySub.find({MALL_CATEGORY_ID:categoryId}).exec()
    ctx.body={code:0,message:result}
  }catch(err){
      ctx.body={code:500,message:err}
  }
})

// 根据商品2级分类，获取商品列表
router.post('/getGoodsListByCategorySubID',async(ctx)=>{
  try{
    let categorySubId = ctx.request.body.categorySubId;
    let page = ctx.request.body.page;
    // console.log(categorySubId, page)
    // let categorySubId = '2c9f6c946016ea9b016016f79c8e0000'
    const Goods = mongoose.model('goods');
    let limitNum = 10;   // 每页显示10条
    let skipNum = (page-1) * limitNum;   // 在搜索结果中，跳过前skipNum条数据
    let result = await Goods.find({SUB_ID:categorySubId}).skip(skipNum).limit(limitNum).exec()
    ctx.body={code:0,message:result}
  }catch(err){
      ctx.body={code:500,message:err}
  }
})

module.exports = router;
